//
//  Venue.m
//  SHPE Conference Companion
//
//  Created by Richard Kirk on 3/25/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Venue.h"
#import "Conference.h"
#import "Location.h"
#import "Session.h"


@implementation Venue
@dynamic name;
@dynamic phone;
@dynamic website;
@dynamic venueName;
@dynamic desc;
@dynamic venueType;
@dynamic id;
@dynamic thumbnailURL;
@dynamic thumbnailData;
@dynamic conference;
@dynamic location;
@dynamic sessions;
@synthesize xmlParser, xmlStringBuilder,parent;

-(id)initWithParser:(NSXMLParser *)parser attributeDict:(NSDictionary *)attributes parent:(id)parentObject
{
    [super initWithEntity:[NSEntityDescription entityForName:@"Venue" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [parser setDelegate:self];
    [self setParent:parentObject];
    
    self.location = [NSEntityDescription insertNewObjectForEntityForName:@"Location" inManagedObjectContext:[self managedObjectContext]];    
    self.id = [NSNumber numberWithInt:[[attributes objectForKey:@"id"] intValue]];
    self.name = [NSString stringWithString:[attributes objectForKey:@"name"]] ;
    self.thumbnailURL = [NSString stringWithString:[attributes objectForKey:@"xlink:thumbnail"]];
    self.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.thumbnailURL]];
    
    
    return self;
}


-(id)initWithVenueId:(int)venueId
{
    [super initWithEntity:[NSEntityDescription entityForName:@"Venue" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];

    
    
    
    self.location = [NSEntityDescription insertNewObjectForEntityForName:@"Location" inManagedObjectContext:[self managedObjectContext]];    
    
    
    xmlParser = [NSXMLParser alloc];
    xmlParser.delegate = self;
    
    [xmlParser initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://openshpe.staging.shpe.org/conference/v1/venue/%d", venueId]]];    
    
    if (xmlParser){
        [xmlParser parse];
    }
    
    
    return self;
}

-(NSString *)description
{
    
    
    return [NSString stringWithFormat:@"\nName : %@\nVenueid : %@\nVenueType : %@\nVenueName : %@\nDesc : %@\nWebsite : %@\nThumbnail URL : %@\nPhone : %@\naddress : %@\ncity : %@\nprovience : %@\ncountry : %@\npostal code : %@\nlat : %@\nlon : %@\n", self.name, self.id, self.venueType, self.venueName, self.desc, self.website, self.thumbnailURL,  self.phone, self.location.address, self.location.city, self.location.province, self.location.country, self.location.postalCode, self.location.lat, self.location.lon];
    
}




- (void)addSessionsObject:(Session *)value {    
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"sessions"] addObject:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)removeSessionsObject:(Session *)value {
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"sessions"] removeObject:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)addSessions:(NSSet *)value {    
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"sessions"] unionSet:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
}

- (void)removeSessions:(NSSet *)value {
    [self willChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"sessions"] minusSet:value];
    [self didChangeValueForKey:@"sessions" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{
    
    if ( ( [elementName isEqualToString:@"conference-venue"] )) {
        self.id = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
        self.name = [NSString stringWithString:[attributeDict objectForKey:@"name"]] ;
        self.thumbnailURL = [NSString stringWithString:[attributeDict objectForKey:@"xlink:thumbnail"]];
       self.thumbnailData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.thumbnailURL]];        return;
    }
    
    if ( ( [elementName isEqualToString:@"coordinate"] )) {
        
        self.location.lat = [NSNumber numberWithFloat:[[attributeDict objectForKey:@"lat"] floatValue]];
        self.location.lon = [NSNumber numberWithFloat:[[attributeDict objectForKey:@"lon"] floatValue]];
        
        return;
    }
    if ( ( [elementName isEqualToString:@"venue-type"] )) {
        self.venueType = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
        self.venueName = [NSString stringWithString:[attributeDict objectForKey:@"name"]] ;
        return;
    }
    
    
    
}



- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{   string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@" & "];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    if (!xmlStringBuilder) {
        xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
    }
    
    [xmlStringBuilder appendString:string];
    
    
}

-(void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString
{    
    
        //Didnt need this 
    /**
     
     NSLog(@"\nfound ignoreable whitespace: whitespace string: \"%@\"\n", whitespaceString);
     if (!xmlStringBuilder) {
     xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
     
     }
     //   if (whitespaceString != @"\n")
     // [xmlStringBuilder appendString:whitespaceString];
     
     */
    
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    
        // ignore root and empty elements
    if ( [elementName isEqualToString:@"location"] ) 
        return;
    
    else if ([elementName isEqualToString:@"conference-venue"] ) {
        [parser setDelegate:parent];
        xmlStringBuilder = nil;
        return;
    }
    
    else if( [elementName isEqualToString:@"description"] ) {
        
        self.desc =[NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"website"] ) {
        self.website = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"phone"] ) {
        self.phone = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"address"] ) {
        self.location.address = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"city"] ) {
        self.location.city = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"province"] ) {
        self.location.province = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"country"] ) {
        self.location.country = [NSString stringWithString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"postalCode"] ) {
        self.location.postalCode = [NSNumber numberWithInt:[xmlStringBuilder intValue]];
        
    }
    
    
    
    xmlStringBuilder = nil;
    
    
    
}



-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    
    NSLog(@"XML ERROR :\n%@\n",[parseError description]);
    
    UIAlertView *parserAlert = [[UIAlertView alloc]init];
    
    
    [parserAlert setTitle:@"Parsing Error!"];
    
    [parserAlert setMessage:[NSString stringWithFormat:@"Error %i, Description: %@, Line: %i, Column: %i", 
                             [parseError code], 
                             [parseError localizedDescription], 
                             [parser lineNumber], 
                             [parser columnNumber]]];
    
    [parserAlert addButtonWithTitle:@"OK"];
    [parserAlert show];
    [parserAlert release];
    
    
    
}



@end
